// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const path = require('path');
const fs = require('fs')
const vscode = require('vscode');

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed

let panel
/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "tetris-for-vscode" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('tetris-for-vscode.play', function () {
		// The code you place here will be executed every time your command is executed

		// Display a message box to the user
		vscode.window.showInformationMessage('TETRIS: Welcome to enjoy Tetris for VSCode!');

		// init webview panel
		if (panel) {
			panel.reveal(vscode.ViewColumn.Active);
		} else {
			panel = vscode.window.createWebviewPanel(
				'tetris',
				'Tetris',
				vscode.ViewColumn.One,
				{
					enableScripts: true, // 启用JS，默认禁用
					retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
				}
			);
			// And get the special URI to use with the webview
			panel.webview.html = getWebViewContent(context, 'src/webview/dist/index.html', panel)

			// Restart after an exception occurs
			panel.webview.onDidReceiveMessage(message => {
				switch (message) {
					case 'error':
						vscode.window.showErrorMessage('TETRIS: Exception occurred, please restart!')
						panel.dispose()
						break
					case 'ok':
						break
				}
			})
			// Panel dispose
			panel.onDidDispose(
        () => {
					panel = null
				},
        null,
        context.subscriptions
      );
			panel.onDidChangeViewState((e) => {
				if (!e.webviewPanel.active) {
					panel.webview.postMessage({ msg: 'pause' })
				}
			})
		}
	});

	context.subscriptions.push(disposable);
}

// This method is called when your extension is deactivated
function deactivate() {}

function getWebViewContent(context, templatePath, panel) {
	const resourcePath = path.join(context.extensionPath, templatePath);
	const dirPath = path.dirname(resourcePath);
	let htmlIndexPath = fs.readFileSync(resourcePath, 'utf-8');

	const html = htmlIndexPath.replace(/(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g, (m, $1, $2) => {
		const absLocalPath = path.resolve(dirPath, $2);
		const webviewUri = panel.webview.asWebviewUri(vscode.Uri.file(absLocalPath));
		const replaceHref = $1 + webviewUri.toString() + '"';
		return replaceHref;
	});
	return html;
}

module.exports = {
	activate,
	deactivate
}
